// app.ts
export const WXAPI = require('apifm-wxapi')
export const CONFIG = require('config.js')
export const AUTH = require('utils/auth')

// WXAPI.init('gooking')

App({
  onLaunch() {
    WXAPI.init(CONFIG.subDomain) // 从根目录的 config.js 文件中读取

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res)
      }
    })

    WXAPI.banners().then(function (res: { code: number; data: any }) {
      if (res.code == 0) {
        console.log("onLaunch ", res.data);
      }
    });

    // 获取所有的文章分类
    WXAPI.cmsCategories().then((res: { code: number; data: any[] }) => {
      if (res.code === 0) {
        res.data.forEach((category: { key: string }) => {
          wx.setStorageSync('news_category_' + category.key, category)
        })
      }
    })

  },
  async onShow(e) {
    if (e && e.query && e.query.cardUid) {
      this.globalData.cardUid = e.query.cardUid
      wx.setStorageSync('referrer', e.query.cardUid)
    }
    // 自动登录
    AUTH.checkHasLogined().then((isLogined: any) => {
      if (!isLogined) {
        AUTH.login()
      }
    })
    
    await WXAPI.queryConfigBatch('mallName,DEFAULT_FRIEND_UID').then(function (res: { code: number; data: any[] }) {
      if (res.code == 0) {
        res.data.forEach((config: { key: string; value: any }) => {
          console.warn(config)
          wx.setStorageSync(config.key, config.value);
        })
      }
    })

  },
  globalData: {
    userInfo: null,
    isConnected: true,
    cardUid: null
  }
})

export { };